package com.example.controller;

import cn.hutool.core.map.MapUtil;
import com.example.POJO.User;
import com.example.Util.JwtUtils;
import com.example.common.Result;
import com.example.common.dto.LoginDto;
import com.example.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping(value="/login"  )
public class Login {

    @Autowired
    UserRepository userRepository;

    @Autowired
    JwtUtils jwtUtils;


    @RequestMapping(value="", method= RequestMethod.POST    )
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {
        User user =  userRepository.findUserByUsername(loginDto.getUsername());
        if (null == user){
            return Result.fail("没有这个用户");
        }
        if (loginDto.getUsername().equals(user.getUsername()) &&     loginDto.getPassword().equals(user.getPassword())  ){

            String jwt = jwtUtils.generateToken(user.getId());

            response.setHeader("Authorization", jwt);
            response.setHeader("Access-control-Expose-Headers", "Authorization");

            return Result.succ(MapUtil.builder()
                    .put("id", user.getId())
                    .put("username", user.getUsername())
                    .put("avatar", user.getAvatar())
                    .put("email", user.getEmail())
                    .map()
            );
        }else {
            return Result.fail("用户名 or 密码 - 错误");
        }
    }




}
